// import { login, logout, getInfo } from '@/api/user'
import userApi from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import router from "@/router";
import {resetRouter} from '@/router'
import { stat } from "fs";
import { Routes, asyncRoutes, anyRoute } from "@/router/routes";
import cloneDeep from 'lodash/cloneDeep'
// const getDefaultState = () => {
//   return {
//     // token: getToken(),
//     // name: '',
//     // avatar: ''
//     token:localStorage.getItem('token_key') || ''
//   }
// }

//筛选异步添加的路由数据的数据-所有的异步路由,用户携带的数据
export const asyncFilterRoutes = (asyncRoutes, Routes) => {
  return  asyncRoutes.filter((item) => {
    // findIndex查找找不到返回-1
    // console.log(Routes.indexOf(item.name) !== -1)
    if (Routes.indexOf(item.name) !== -1) {
      // 筛渲
      if (item.children && item.children.length) {
        item.children =  asyncFilterRoutes(item.children,Routes)
      }
      return true
    }
  });
};

// 将获取到的动态路由动态的添加到静态路由当中
export const addAsyncRoutes = (Routes) => {
  router.addRoutes(Routes)
};

// 重置路由
export const resetAsync = ()=>{
    
}

const state = {
  token: localStorage.getItem("token_key") || "",
  userInfo: {},
  //  路由遍历的数组
  routes: Routes,
  buttons:[]
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo;
  },
  RESET_TOKEN: (state) => {
    state.token = "";
    // state.userInfo = {};
    Object.assign(state.userInfo,{name: '',avatar: ''})
  },
  SET_ROUTES:(state,routes)=>{
    state.routes = routes
  },
  SET_BUTTONS:(state,buttons)=>{
    state.buttons = buttons
  }
  // RESET_STATE: (state) => {
  //   Object.assign(state, getDefaultState())
  // },
  // SET_TOKEN: (state, token) => {
  //   state.token = token
  // },
  // SET_NAME: (state, name) => {
  //   state.name = name
  // },
  // SET_AVATAR: (state, avatar) => {
  //   state.avatar = avatar
  // }
};

const actions = {
  // 登录
  async login({ commit }, userInfo) {
    try {
      let result = await userApi.login(userInfo);
      // console.log(result.token,'token')
      localStorage.setItem("token_key", result.token);
      commit("SET_TOKEN", result.token);
      // this.$router.push('/')
      return "ok";
    } catch (error) {
      console.log(error);
      return Promise.reject(error);
    }
  },
  // 获取用户信息
  async getInfo({ commit,state}) {
    // console.log(state,'state')
    try {
      let result = await userApi.getInfo();
      let { name, avatar } = result;
      // console.log(result.buttons,'result');
      // 筛选需要动态添加的路由的数组的结合
       let asyncRouteList = asyncFilterRoutes(cloneDeep(asyncRoutes),result.routes)
      addAsyncRoutes(asyncRouteList.concat(anyRoute))
    commit('SET_ROUTES',Routes.concat(asyncRouteList,anyRoute))
    commit('SET_BUTTONS',result.buttons)
      commit("SET_USERINFO", { name, avatar });
    } catch (error) {
      console.log(error);
      return Promise.reject(error);
    }
  },

  // 退出登录的时候-重置token
  resetToken({ commit }) {
    // 清除token
    commit("RESET_TOKEN");
    // 清除localstorage的token
    localStorage.removeItem("token_key");
    // 清空用户信息
    resetRouter()
  },

  // 退出登录
  async logout({ commit, dispatch }) {
    try {
      await userApi.logout();
      dispatch("resetToken");
      // 需要将路由进行重置
      return "ok";
    } catch (error) {
      return Promise.reject(error);
    }
  },

  // // get user info
  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.token).then(response => {
  //       const { data } = response

  //       if (!data) {
  //         return reject('Verification failed, please Login again.')
  //       }

  //       const { name, avatar } = data

  //       commit('SET_NAME', name)
  //       commit('SET_AVATAR', avatar)
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // // user logout
  // logout({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     logout(state.token).then(() => {
  //       removeToken() // must remove  token  first
  //       resetRouter()
  //       commit('RESET_STATE')
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // // remove token
  // resetToken({ commit }) {
  //   return new Promise(resolve => {
  //     removeToken() // must remove  token  first
  //     commit('RESET_STATE')
  //     resolve()
  //   })
  // }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
